package com.aiyige.page.publish.editbanner;

import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Rect;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.aiyige.R;
import com.aiyige.arouter.config.ARouterConfig;
import com.aiyige.base.BaseActivity;
import com.aiyige.model.moment.entity.Moment;
import com.aiyige.page.my.settings.ConfigUltis;
import com.aiyige.page.publish.coursedescription.CourseDescriptionPage;
import com.aiyige.page.publish.coursedescription.model.CourseCover;
import com.aiyige.page.publish.editbanner.adapter.EditBannerAdapter;
import com.aiyige.page.publish.util.PublishUtil;
import com.aiyige.utils.FileUtil;
import com.aiyige.utils.ImageCropper;
import com.aiyige.utils.ListUtil;
import com.aiyige.utils.ToastX;
import com.aiyige.utils.UIHelper;
import com.aiyige.utils.VideoUtil;
import com.aiyige.utils.dialog.LoadingDialog;
import com.aiyige.utils.widget.CommonBottomDialogFragment;
import com.aiyige.utils.widget.GprsNotificationDialogUtil;
import com.alibaba.android.arouter.facade.Postcard;
import com.alibaba.android.arouter.facade.annotation.Autowired;
import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.config.PictureMimeType;
import com.luck.picture.lib.entity.LocalMedia;
import com.vondear.rxtools.RxNetTool;
import com.yalantis.ucrop.UCrop;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

@Route(path = ARouterConfig.EditBannerPage)
public class EditBannerPage extends AppCompatActivity {
    public static final int REQUEST_CODE_ADD_COVER = 0x1123;
    public static final String EXTRA_KEY_BANNER_DATA = "com.aiyige.extra.EXTRA_KEY_BANNER_DATA";

    @BindView(R.id.titleBackBtn)
    ImageView titleBackBtn;
    @BindView(R.id.titleTv)
    TextView titleTv;
    @BindView(R.id.titleActionBtn)
    TextView titleActionBtn;
    @BindView(R.id.mainRv)
    RecyclerView mainRv;
    EditBannerAdapter editBannerAdapter;
    CommonBottomDialogFragment courseDescCoverPhotoEditDialog;
    CommonBottomDialogFragment courseDescCoverVideoEditDialog;
    @Autowired
    CourseCover[] preSelectArray;
    List<CourseCover> preSelectList;
    int cropPosition = 0;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.page_edit_banner);
        ButterKnife.bind(this);
        ARouter.getInstance().inject(this);
        preSelectList = new LinkedList<>();
        if (preSelectArray != null && preSelectArray.length != 0) {
            for (CourseCover item : preSelectArray) {
                preSelectList.add(item);
            }
        }
        titleTv.setText(R.string.select_cover);
        titleActionBtn.setText(R.string.finish);
        mainRv.setItemAnimator(null);
        mainRv.setLayoutManager(new GridLayoutManager(this, 2));
        mainRv.addItemDecoration(new RecyclerView.ItemDecoration() {
            @Override
            public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
                super.getItemOffsets(outRect, view, parent, state);
                int index = parent.getChildAdapterPosition(view);
                if (index % 2 == 0) {
                    outRect.set(UIHelper.dp2px(9), UIHelper.dp2px(15), UIHelper.dp2px(8), 0);
                } else {
                    outRect.set(UIHelper.dp2px(1), UIHelper.dp2px(15), UIHelper.dp2px(15), 0);
                }
            }
        });
        editBannerAdapter = new EditBannerAdapter();
        editBannerAdapter.bindToRecyclerView(mainRv);
        editBannerAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                CourseCover courseCover = editBannerAdapter.getItem(position);
                switch (courseCover.getType()) {
                    case CourseCover.TYPE_ADD:
                        PictureSelector.create(EditBannerPage.this)
                                .openGallery(PictureMimeType.ofAll())
                                .minSelectNum(1)
                                .maxSelectNum(PublishUtil.MAX_COURSE_DESCRIPTION_COVER_NUM)
                                .selectionMode(PictureConfig.MULTIPLE)
                                .previewImage(false)
                                .previewVideo(false)
                                .enableCrop(false)
                                .isCamera(false)
                                .compress(false)
                                .imageSpanCount(4)
                                .selectionMedia(getSelectedCover())
                                .forResult(REQUEST_CODE_ADD_COVER);
                        break;
                    case CourseCover.TYPE_NORMAL:
                        switch (courseCover.getMediaType()) {
                            case CourseCover.MEDIA_TYPE_PHOTO:
                                courseDescCoverPhotoEditDialog.setPosition(position);
                                courseDescCoverPhotoEditDialog.show(getSupportFragmentManager(), "");
                                break;
                            case CourseCover.MEDIA_TYPE_VIDEO:
                                courseDescCoverVideoEditDialog.setPosition(position);
                                courseDescCoverVideoEditDialog.show(getSupportFragmentManager(), "");
                                break;
                        }
                        break;
                }
            }
        });


        courseDescCoverPhotoEditDialog = CommonBottomDialogFragment.newBuilder()
                .listener(new CommonBottomDialogFragment.Listener() {
                    @Override
                    public void onViewClicked(int position, View view) {
                        switch (view.getId()) {
                            case R.id.deleteBtn:
                                editBannerAdapter.remove(position);
                                if (editBannerAdapter.getItem(editBannerAdapter.getData().size() - 1).getType() != CourseCover.TYPE_ADD) {
                                    editBannerAdapter.addData(CourseCover.newBuilder()
                                            .type(CourseCover.TYPE_ADD)
                                            .build());
                                }
                                autoConfigDefaultCoverIfNotExist();
                                break;
                            case R.id.setAsDefaultCoverBtn:
                                for (int i = 0; i < editBannerAdapter.getData().size(); ++i) {
                                    editBannerAdapter.getItem(i).setDefaultCover(i == position);
                                }
                                editBannerAdapter.notifyDataSetChanged();
                                break;
                            case R.id.cropCoverBtn:
                                cropPosition = position;
                                ImageCropper.newBuilder()
                                        .activity(EditBannerPage.this)
                                        .aspectRatioX(16)
                                        .aspectRatioY(9)
                                        .path(editBannerAdapter.getItem(position).getImageUrl())
                                        .build()
                                        .startCrop();
                                break;
                        }
                    }
                })
                .layoutResId(R.layout.course_desc_cover_photo_edit_dialog)
                .viewIdList(R.id.cropCoverBtn, R.id.setAsDefaultCoverBtn, R.id.deleteBtn, R.id.cancelBtn)
                .build();

        courseDescCoverVideoEditDialog = CommonBottomDialogFragment.newBuilder()
                .listener(new CommonBottomDialogFragment.Listener() {
                    @Override
                    public void onViewClicked(int position, View view) {
                        switch (view.getId()) {
                            case R.id.deleteBtn:
                                editBannerAdapter.remove(position);
                                if (editBannerAdapter.getItem(editBannerAdapter.getData().size() - 1).getType() != CourseCover.TYPE_ADD) {
                                    editBannerAdapter.addData(CourseCover.newBuilder()
                                            .type(CourseCover.TYPE_ADD)
                                            .build());
                                }
                                autoConfigDefaultCoverIfNotExist();
                                break;
                        }
                    }
                })
                .layoutResId(R.layout.course_desc_cover_video_edit_dialog)
                .viewIdList(R.id.deleteBtn, R.id.cancelBtn)
                .build();
        restoreData();
    }

    public void autoConfigDefaultCoverIfNotExist() {
        boolean existDefaultCover = false;
        for (CourseCover courseCover : editBannerAdapter.getData()) {
            if (courseCover.getType() == CourseCover.TYPE_NORMAL && courseCover.getMediaType() == CourseCover.MEDIA_TYPE_PHOTO && courseCover.isDefaultCover()) {
                existDefaultCover = true;
                break;
            }
        }
        if (!existDefaultCover) {
            for (CourseCover courseCover : editBannerAdapter.getData()) {
                if (courseCover.getType() == CourseCover.TYPE_NORMAL && courseCover.getMediaType() == CourseCover.MEDIA_TYPE_PHOTO) {
                    courseCover.setDefaultCover(true);
                    break;
                }
            }
            editBannerAdapter.notifyDataSetChanged();
        }
    }

    public CourseCover getDefaultCourseCover() {
        for (CourseCover courseCover : editBannerAdapter.getData()) {
            if (courseCover.getType() == CourseCover.TYPE_NORMAL
                    && courseCover.getMediaType() == CourseCover.MEDIA_TYPE_PHOTO
                    && courseCover.isDefaultCover()) {
                return courseCover;
            }
        }
        return null;
    }

    public boolean checkFormValidate() {
        if (getDefaultCourseCover() == null) {
            ToastX.show(R.string.must_select_a_photo_as_default_cover);
            return false;
        } else {
            return true;
        }
    }

    private List<CourseCover> getRealCover() {
        List<CourseCover> realCoverList = new LinkedList<>();
        for (CourseCover courseCover : editBannerAdapter.getData()) {
            if (courseCover.getType() != CourseCover.TYPE_ADD) {
                realCoverList.add(courseCover);
            }
        }
        return realCoverList;
    }


    public void restoreData() {
        editBannerAdapter.setNewData(preSelectList);
        if (editBannerAdapter.getData().size() < PublishUtil.MAX_COURSE_DESCRIPTION_COVER_NUM) {
            editBannerAdapter.addData(CourseCover.newBuilder().type(CourseCover.TYPE_ADD).build());
        }
    }

    public List<LocalMedia> getSelectedCover() {
        List<LocalMedia> localMediaList = new LinkedList<>();
        List<CourseCover> realCourseCoverList = getRealCover();
        for (CourseCover courseCover : realCourseCoverList) {
            LocalMedia localMedia = new LocalMedia();
            switch (courseCover.getMediaType()) {
                case CourseCover.MEDIA_TYPE_PHOTO:
                    localMedia.setPictureType("image/*");
                    localMedia.setMimeType(PictureConfig.TYPE_PICTURE);
                    localMedia.setPath(courseCover.getImageUrl());
                    break;
                case CourseCover.MEDIA_TYPE_VIDEO:
                    localMedia.setPictureType("video/mp4");
                    localMedia.setMimeType(PictureConfig.TYPE_VIDEO);
                    localMedia.setPath(courseCover.getVideoUrl());
                    break;
            }
            localMediaList.add(localMedia);
        }
        return localMediaList;
    }

    @OnClick({R.id.titleBackBtn, R.id.titleActionBtn})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.titleBackBtn:
                finish();
                break;
            case R.id.titleActionBtn:
                if (!checkFormValidate()) return;
                Intent data = new Intent();
                data.putExtra(EXTRA_KEY_BANNER_DATA, new ArrayList<>(getRealCover()));
                setResult(RESULT_OK, data);
                finish();
                break;
        }
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        switch (requestCode) {
            case REQUEST_CODE_ADD_COVER:
                if (resultCode == RESULT_OK) {
                    List<LocalMedia> selectList = PictureSelector.obtainMultipleResult(data);
                    if (!ListUtil.isEmpty(selectList)) {
                        new HandleSelectCoverTask(getRealCover(), selectList).execute();
                    }
                }
                break;
            case UCrop.REQUEST_CROP:
                if (resultCode == RESULT_OK) {
                    try {
                        Uri resultUri = UCrop.getOutput(data);
                        String cutPath = resultUri.getPath();
                        CourseCover courseCover = editBannerAdapter.getItem(cropPosition);
                        courseCover.setImageUrl(cutPath);
                        editBannerAdapter.setData(cropPosition, courseCover);
                    } catch (Exception e) {
                    }
                }
                break;
            default:
                super.onActivityResult(requestCode, resultCode, data);
                break;
        }
    }

    public class HandleSelectCoverTask extends AsyncTask<Object, Object, Object> {
        LoadingDialog loadingDialog;
        List<CourseCover> courseCoverList;
        List<LocalMedia> localMediaList;

        public HandleSelectCoverTask(List<CourseCover> courseCoverList, List<LocalMedia> localMediaList) {
            this.courseCoverList = new LinkedList<>(courseCoverList);
            this.localMediaList = new LinkedList<>(localMediaList);
        }

        @Override
        protected void onPreExecute() {
            loadingDialog = LoadingDialog.newBuilder()
                    .with(EditBannerPage.this)
                    .cancelable(false)
                    .message(R.string.text_process)
                    .show();
        }

        public boolean checkExist(LocalMedia localMedia) {
            for (CourseCover courseCover : courseCoverList) {
                if (localMedia.getPictureType().startsWith("image")) {
                    if (localMedia.getPath().equals(courseCover.getImageUrl())) {
                        return true;
                    }
                } else {
                    if (localMedia.getPath().equals(courseCover.getVideoUrl())) {
                        return true;
                    }
                }
            }
            return false;
        }

        public void merge() {
            Iterator<CourseCover> courseCoverIterator = courseCoverList.iterator();
            outerLoop:
            while (courseCoverIterator.hasNext()) {
                CourseCover courseCover = courseCoverIterator.next();
                Iterator<LocalMedia> localMediaIterator = localMediaList.iterator();
                while (localMediaIterator.hasNext()) {
                    LocalMedia localMedia = localMediaIterator.next();
                    if (localMedia.getPictureType().startsWith("image")) {
                        if (localMedia.getPath().equals(courseCover.getImageUrl())) {
                            localMediaIterator.remove();
                            continue outerLoop;
                        }
                    } else {
                        if (localMedia.getPath().equals(courseCover.getVideoUrl())) {
                            localMediaIterator.remove();
                            continue outerLoop;
                        }
                    }
                }
                courseCoverIterator.remove();
            }
        }


        @Override
        protected Object doInBackground(Object... objects) {
            try {
                merge();
                for (LocalMedia localMedia : localMediaList) {
                    if (localMedia.getPictureType().startsWith("image")) {
                        CourseCover courseCover = CourseCover.newBuilder()
                                .defaultCover(false)
                                .mediaType(CourseCover.MEDIA_TYPE_PHOTO)
                                .size(FileUtil.getFileSize(localMedia.getPath()))
                                .imageUrl(localMedia.getPath())
                                .type(CourseCover.TYPE_NORMAL)
                                .build();
                        courseCoverList.add(courseCover);
                    } else {
                        CourseCover courseCover = CourseCover.newBuilder()
                                .defaultCover(false)
                                .videoUrl(localMedia.getPath())
                                .imageUrl(VideoUtil.getVideoCover(localMedia.getPath(), 0))
                                .mediaType(CourseCover.MEDIA_TYPE_VIDEO)
                                .duration(localMedia.getDuration())
                                .size(FileUtil.getFileSize(localMedia.getPath()))
                                .type(CourseCover.TYPE_NORMAL)
                                .build();
                        courseCoverList.add(courseCover);
                    }
                }
                return null;
            } catch (Exception e) {
                return e;
            }

        }

        @Override
        protected void onPostExecute(Object o) {
            loadingDialog.dismiss();
            if (o instanceof Exception) {
                ToastX.show(((Exception) o).getMessage());
            } else {
                if (courseCoverList.size() < PublishUtil.MAX_COURSE_DESCRIPTION_COVER_NUM) {
                    courseCoverList.add(CourseCover.newBuilder().type(CourseCover.TYPE_ADD).build());
                }
                editBannerAdapter.setNewData(courseCoverList);
                autoConfigDefaultCoverIfNotExist();
            }
        }
    }


}
